package api

import (
	"buding-ai/internal/web/response"
	"buding-ai/pkg/utils/jwt"
	"errors"
	"github.com/gin-gonic/gin"
	"strconv"
)

type BaseApi struct {
}

// BindJSON 绑定JSON请求
func (b *BaseApi) BindJSON(c *gin.Context, obj interface{}) error {
	return c.ShouldBindJSON(obj)
}

// BindForm 绑定表单请求
func (b *BaseApi) BindForm(c *gin.Context, obj interface{}) error {
	return c.ShouldBind(obj)
}

// GetParam 获取RESTful风格的URL参数
func (b *BaseApi) GetParam(c *gin.Context, key string) string {
	return c.Param(key)
}

func (b *BaseApi) GetParamUint(c *gin.Context, key string) (uint, error) {
	param := c.Param(key)
	val, err := strconv.ParseUint(param, 10, 64)
	return uint(val), err
}

func (b *BaseApi) GetParamWithConvert(c *gin.Context, key string, converter func(string) (interface{}, error)) (interface{}, error) {
	param := c.Param(key)
	return converter(param)
}

// GetQuery 获取查询参数
func (b *BaseApi) GetQuery(c *gin.Context, key string) (string, bool) {
	return c.GetQuery(key)
}

func (b *BaseApi) GetQueryUint(c *gin.Context, key string) (uint, error) {
	param, flag := c.GetQuery(key)
	if !flag {
		return 0, errors.New("获取不到id参数")
	}
	val, err := strconv.ParseUint(param, 10, 64)
	return uint(val), err
}

func (b *BaseApi) CurrentUser(ctx *gin.Context) (*jwt.Claims, error) {
	claims, exists := ctx.Get("claims")
	if !exists {
		response.Unauthorized(ctx, "未认证")
		return nil, errors.New("未认证")
	}

	// 将声明转换为JWT声明对象
	jwtClaims, ok := claims.(*jwt.Claims)
	if !ok {
		response.InternalError(ctx, "无效的JWT声明", nil)
		return nil, errors.New("无效的JWT声明")
	}
	return jwtClaims, nil
}
